﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Snowdreamist.Windows.Navigation.Primitives
{
    public class NavigationHandlerSelector
    {
        public NavigationHandlerSelector(NavigationHandlerRepository repository)
        {
            if (repository == null)
                throw new ArgumentNullException("repository");
            this.Repository = repository;
            this.Mappers = new UriMapperRepository();
            this.UriPrefix = new UriPrefixSelector();
        }

        public NavigationHandlerRepository Repository { get; private set; }

        public UriMapperRepository Mappers { get; private set; }

        public UriPrefixSelector UriPrefix { get; private set; }

        public INavigationHandler Select(Uri uri)
        {
            if (uri == null)
                throw new ArgumentNullException("uri");

            string uriStr = uri.ToString();
            // map uri
            while (true)
            {
                bool isMapped = false;

                foreach (var mapper in this.Mappers.Mappers)
                    isMapped = mapper.Map(ref uriStr);

                if (!isMapped)
                    break;
            }
            // prefix
            var handlerName = this.UriPrefix.Select(uriStr);
            if (string.IsNullOrWhiteSpace(handlerName))
                return null;
            // get
            return this.Repository.GetHandler(handlerName);
        }
    }
}